<template>
  <h2>组合式api的改写</h2>
  <button @click="minus">-</button>
  <span>{{ count }}</span>
  <button @click="add">+</button>

  <hr />

  <input type="text" v-model="value" />
  <button @click="push">添加</button>
  <ul>
    <li v-for="item in list" :key="item.id">
      {{ item.name }} - <button @click="remove(item.id)">删除</button>
    </li>
  </ul>
</template>

<script>
// 如果要使用响应式，需要引入ref
import { ref } from "vue";
import counter from "./utils/counter";

export default {
  // setup函数就是组合式api的入口
  // 有了setup，就几乎不需要其他的选项了
  // 会自动执行，并且没有this
  setup() {
    // console.log(123, this);

    const { count, add, minus } = counter();
    const { list, value, push, remove } = todolist();

    return { count, add, minus, list, value, push, remove };
  },
};

const todolist = () => {
  const list = ref([
    {
      id: 1,
      name: "zhangsan",
    },
    {
      id: 2,
      name: "lisi",
    },
  ]);
  const value = ref("");
  const push = () => {
    list.value.push({
      id: new Date().getTime(),
      name: value.value,
    });
    value.value = "";
  };
  const remove = (id) => {
    list.value = list.value.filter((item) => item.id !== id);
  };

  return { list, value, push, remove };
};
</script>
